// pages/manage/manage.js

var QQMapWX = require('../../common/qqmap-wx-jssdk.js');
var qqmapsdk;
var app = getApp();

Page({

	data: {
		currentTab: 1,// tab切换 
		isEdit: false,//默认是发布新职位
		agreement: false,//协议
		
		checkTempUI: 1,//模版选择UI,默认企业
		checkTempIndex: 0,//默认选择
		checkTemp: true,//模版选择
		animationCheckTemp:{},//模版动画
		contentObj:{},//模版对象
		positionContent: true,//职位描述
		animationPositionContent:{},//职位动画

		positionObj:{},

		//组件
		nextPageUrl: true,
		pageNum: 1,
		positions: [],
		height: 0,
		scrollY: true,

		//字典
		workYearsIndex:0,
		eduIndex:1,

		mask: true,//组件alert
		animationData: {},//组件alert
		alertTitle: '提示',//组件alert
		alertPlaceholder: '请输入内容',//组件alert
		alertTip: '例如：输入一段文字',//组件alert
		alertTextareaVal: '',//组件alert
		element: '',//触发事件的节点
	},
	swipeCheckX: 35, //激活检测滑动的阈值
	swipeCheckState: 0, //0未激活 1激活
	maxMoveLeft: 85, //消息列表项最大左滑距离
	correctMoveLeft: 75, //显示菜单时的左滑距离
	thresholdMoveLeft: 30,//左滑阈值，超过则显示菜单
	lastShowMsgId: '', //记录上次显示菜单的消息id
	moveX: 0,  //记录平移距离
	showState: 0, //0 未显示菜单 1显示菜单
	touchStartState: 0, // 开始触摸时的状态 0 未显示菜单 1 显示菜单
	swipeDirection: 0, //是否触发水平滑动 0:未触发 1:触发水平滑动 2:触发垂直滑动


	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		this.pixelRatio = app.globalData.systemInfo.pixelRatio;
		var windowHeight = app.globalData.systemInfo.windowHeight;
		var height = windowHeight;
		
		this.setData({ 
			height: height 
		});

		this.getTypelist();

		// 实例化API核心类
		qqmapsdk = new QQMapWX({
			key: 'ZHBBZ-2MX6F-MMHJS-J6KN6-NGS5H-TLBWG'
		});

		this.getTemplates();
		this.getMyJobs(this.data.pageNum);
    app.alert('左划职位有更多操作哦~');
	},
	
	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {

		

	},
  bindNextPage:function(){
    if (this.data.nextPageUrl) {
      this.getMyJobs(this.data.pageNum);
    }
  },
	//字典
	getTypelist: function(){
		var that = this;
		//年限
		app.apiGet(app.apiList.typelist, { type:1},function(res){
			if(res.code == 200){
				that .setData({
					workYearsArray: res.data
				})
			}
		})

		//学历
		app.apiGet(app.apiList.typelist, { type: 2}, function (res) {
			if (res.code == 200) {
				that.setData({
					eduArray: res.data
				})
			}
		})
	},
	//获取模版
	getTemplates: function(){
		var that = this;
		app.apiGet(app.apiList.template, { }, function (res) {
			if (res.code == 200) {
				var templateQiye = [], templateShiwusuo = [];
				//1公司，2事务所
				for (var i = 0; i<res.data.length;i++){
					if (res.data[i].type == 1){
						templateQiye.push(res.data[i])
					} else if (res.data[i].type == 2){
						templateShiwusuo.push(res.data[i])
					}
				}
				that.setData({
					templateQiye: templateQiye,
					templateShiwusuo: templateShiwusuo,
					templates: templateQiye
				})
			}
		})
	},
	//选择模版
	bindChangeTemp: function(e){
		this.data.checkTempIndex = e.detail.value
	},
	//选择企业 事务所模版
	changeTempTap: function(){
		if (this.data.checkTempUI == 1){
			this.setData({
				checkTempUI:2,
				templates: this.data.templateShiwusuo
			})
		}else{
			this.setData({
				checkTempUI: 1,
				templates: this.data.templateQiye
			})
		}
	},
	//取消模版
	checkTempCloseTap: function(){
		var animation = wx.createAnimation({
			duration: 200,
			timingFunction: 'linear'
		})
		animation.bottom('-540rpx').step()

		this.setData({
			checkTemp: true,
			animationCheckTemp: animation.export(),
		})
	},
	//确定模版
	checkTempSureTap: function(){
		var that = this;
		if (that.data.contentObj.content){
			wx.showModal({
				title: '提示',
				content: '您选择的模版将覆盖之前的内容，您确定吗',
				success: function (res) {
					if (res.confirm) {
						if (that.data.checkTempUI == 1) {
							let valObj = that.data.templateQiye[that.data.checkTempIndex];
							that.setData({
								contentObj: valObj
							})
						} else {
							let valObj = that.data.templateQiye[that.data.checkTempIndex];
							that.setData({
								contentObj: valObj
							})
						}
						that.checkTempCloseTap();
					} else if (res.cancel) {
						console.log('用户点击取消')
					}
				}
			})
		}else{
			if (that.data.checkTempUI == 1) {
				let valObj = that.data.templateQiye[that.data.checkTempIndex];
				that.setData({
					contentObj: valObj
				})
			} else {
				let valObj = that.data.templateQiye[that.data.checkTempIndex];
				that.setData({
					contentObj: valObj
				})
			}
			that.checkTempCloseTap();
		}

		
	},
	//打开模版
	btnTemplate: function(){
		var animation = wx.createAnimation({
			duration: 200,
			timingFunction: 'linear'
		})
		animation.bottom('0').step()

		this.setData({
			checkTemp: false,
			animationCheckTemp: animation.export(),
		})
		
	},
	//职位描述
	contentTap: function(e){
		var animation = wx.createAnimation({
			duration: 200,
			timingFunction: 'linear'
		})
		animation.bottom('0').step()

		this.setData({
			positionContent: false,
			animationPositionContent: animation.export(),
			positionContentVal: this.data.contentObj.content ? this.data.contentObj.content:''
		})
	},
	positionContentCloseTap: function(){
		var animation = wx.createAnimation({
			duration: 200,
			timingFunction: 'linear'
		})
		animation.bottom('-928rpx').step()

		this.setData({
			positionContent: true,
			animationPositionContent: animation.export(),
		})
	},
	positionContentValTap: function(e){
		this.data.positionContentVal = e.detail.value;
	},
	positionContentSureTap: function(){
		this.setData({
			'contentObj.content': this.data.positionContentVal
		})
		this.positionContentCloseTap();
	},
	//岗位名称
	nameTap: function(e){
		this.data.positionObj.name = e.detail.value;
	},
	//岗位薪资
	salaryTap: function(e){
		this.data.positionObj.salary = e.detail.value;
	},
	//岗位年限
	bindPickerChangeWorkYears: function (e) {
		this.setData({
			workYearsIndex: e.detail.value
		})
	},
	//岗位学历
	bindPickerChangeEdu: function (e) {
		this.setData({
			eduIndex: e.detail.value
		})
	},
	//职位诱惑
	positionFlagTap: function(){
		this.setData({
			alertTitle: '职位诱惑',//组件alert
			alertPlaceholder: '请输入职位诱惑内容',//组件alert
			alertTip: '例如：环境好 热门领域 高成长',//组件alert
			element: 'positionFlag',
		})
		this.showActionVal();
	},
	//公司名称
	companyNameTap: function(e){
		this.data.positionObj.company_name = e.detail.value;
	},
	//公司标签
	companyTagTap: function(){
		this.setData({
			alertTitle: '公司标签',//组件alert
			alertPlaceholder: '请输入公司标签内容',//组件alert
			alertTip: '例如：A轮 50-100人 移动互联网-金融',//组件alert
			element: 'companyTag',
		})
		this.showActionVal();
	},

	//选择行业
	industryTap:function(e){
		var index = e.currentTarget.dataset.index;
		wx.navigateTo({
			url: '/pages/industry/industry?index='+index,
		})
	},
	//选择公司地址
	checkAddressTap: function () {
		var that = this;
		wx.authorize({
			scope: 'scope.userLocation',
			success() {
				console.log('authorize success(scope.userLocation)');
			},
			fail() {
				console.log('authorize fail(scope.userLocation)');
			}
		})
		wx.chooseLocation({
			success: function (res) {
				
				that.setData({
					'positionObj.address': res.address
				})
				//根据坐标获取当前位置名称，显示在顶部:腾讯地图逆地址解析
				qqmapsdk.reverseGeocoder({
					location: {
						latitude: res.latitude,
						longitude: res.longitude
					},
					success: function (addressRes) {
						let data = addressRes.result.address_component;
						if (data.province == data.city){
							data.city = data.district;
						}
						that.data.positionObj.province = data.province;
						that.data.positionObj.city = data.city
						
					}
				})
			},
			fail: function () {

			},
			complete: function () {

			}
		})
	},
	//简历邮箱
	emailTap: function(e){
		this.data.positionObj.email = e.detail.value;
	},
	//协议状态
	checkboxChange: function (e) {
		this.setData({
			agreement: this.data.agreement? false: true
		})
	},

	//保存职位
	submitTap: function(){
		var that = this;
		if (this.data.positionObj.name == undefined || this.data.positionObj.name == '') {
			app.alert('请填写招聘岗位');
			return false;
		}
		if (this.data.positionObj.salary == undefined || this.data.positionObj.salary == '') {
			app.alert('请填写岗位薪资');
			return false;
		}
		if (this.data.positionObj.positionFlag == undefined || this.data.positionObj.positionFlag == '') {
			app.alert('请填写职位诱惑');
			return false;
		}
		if (this.data.positionObj.company_name == undefined || this.data.positionObj.company_name == '') {
			app.alert('请填写公司名称');
			return false;
		}
		if (!this.data.positionObj.industry) {
			app.alert('请选择所属行业');
			return false;
		}
		if (this.data.positionObj.companyTag == undefined || this.data.positionObj.companyTag == '') {
			app.alert('请填写公司标签');
			return false;
		}
		if (this.data.positionObj.address == undefined || this.data.positionObj.address == '') {
			app.alert('请选择公司地址');
			return false;
		}

		if (this.data.positionObj.email == undefined || this.data.positionObj.email == '') {
			app.alert('请填写简历邮箱');
			return false;
		}
		if (!/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/.test(this.data.positionObj.email)) {
			app.alert('邮箱格式不对！');
			return false;
		}
		if (this.data.contentObj.content == undefined || this.data.contentObj.content == ''){
			app.alert('请填写职位描述');
			return false;
		}
		if (!this.data.agreement){
			app.alert('请阅读并同意《相关条款》');
			return false;
		}

		let dataJson = {
			name: this.data.positionObj.name,
			email: this.data.positionObj.email,
			salary: this.data.positionObj.salary,
			required_year: this.data.workYearsArray[this.data.workYearsIndex].id,
			required_edu: this.data.eduArray[this.data.eduIndex].id,
			attract: this.data.positionObj.positionFlag,
			company_name: this.data.positionObj.company_name,
			industry: this.data.positionObj.industry.id,
			tag: this.data.positionObj.companyTag,
			address: this.data.positionObj.address,
			content: this.data.contentObj.content,
			province: this.data.positionObj.province,
			city: this.data.positionObj.city,
		}
		console.log(dataJson)
		app.loading();
		if(that.data.isEdit){
			dataJson.id = that.data.idEdit;
			app.apiPost(app.apiList.editMyJob, dataJson, function (res) {
				app.hideloading();
				if (res.code == 200) {
					wx.showToast({
						title: '修改成功！',
						icon: 'success',
						duration: 1000,
						mask: true,
						success: function () {
							that.data.positions = [];
							that.data.pageNum = 1;
							that.getMyJobs(that.data.pageNum);
							that.setData({
								currentTab: 1
							})
						}
					})
				} else {
					app.alert(res.message);
				}
			})
		}else{
			app.apiPost(app.apiList.createJob, dataJson, function (res) {
				app.hideloading();
				if (res.code == 200) {
					wx.showToast({
						title: '创建成功！',
						icon: 'success',
						duration: 1000,
						mask: true,
						success: function () {
							that.data.positions = [];
							that.data.pageNum = 1;
							that.getMyJobs(that.data.pageNum);
							that.setData({
								currentTab: 1
							})
						}
					})
				} else {
					app.alert(res.message);
				}
			})
		}
		
	},


	//关闭 alert组件
	closeActionVal: function () {
		var animation = wx.createAnimation({
			duration: 200,
			timingFunction: 'linear',
		})
		animation.bottom('-640rpx').step()
		this.setData({
			mask: true,
			animationData: animation.export(),
			alertTextareaVal: ''
		})
	},
	//打开 alert组件
	showActionVal: function () {
		var animation = wx.createAnimation({
			duration: 200,
			timingFunction: 'linear'
		})
		animation.bottom('0').step()

		this.setData({
			mask: false,
			animationData: animation.export(),
		})

		//缓存
		if (this.data.positionObj.positionFlag && this.data.element == 'positionFlag') {
			this.setData({
				alertTextareaVal: this.data.positionObj.positionFlag
			})
		} else if (this.data.positionObj.companyTag && this.data.element == 'companyTag') {
			this.setData({
				alertTextareaVal: this.data.positionObj.companyTag
			})
		} 
	},
	//获取alert textarea里的值
	alertTextareaValTap: function (e) {
		this.data.alertTextareaVal = e.detail.value;
	},
	//确定 alert组件
	alertActionSureTap: function (e) {

		if (this.data.element == 'positionFlag') {
			this.setData({
				'positionObj.positionFlag': this.data.alertTextareaVal
			})
		} else if (this.data.element == 'companyTag') {
			this.setData({
				'positionObj.companyTag': this.data.alertTextareaVal
			})
		}
		this.closeActionVal();
	},



	ontouchstart: function (e) {
		if (this.showState === 1) {
			this.touchStartState = 1;
			this.showState = 0;
			this.moveX = 0;
			this.translateXMsgItem(this.lastShowMsgId, 0, 200);
			this.lastShowMsgId = "";
			return;
		}
		this.firstTouchX = e.touches[0].clientX;
		this.firstTouchY = e.touches[0].clientY;
		if (this.firstTouchX > this.swipeCheckX) {
			this.swipeCheckState = 1;
		}
		this.lastMoveTime = e.timeStamp;
	},

	ontouchmove: function (e) {
		if (this.swipeCheckState === 0) {
			return;
		}
		//当开始触摸时有菜单显示时，不处理滑动操作
		if (this.touchStartState === 1) {
			return;
		}
		var moveX = e.touches[0].clientX - this.firstTouchX;
		var moveY = e.touches[0].clientY - this.firstTouchY;
		//已触发垂直滑动，由scroll-view处理滑动操作
		if (this.swipeDirection === 2) {
			return;
		}
		//未触发滑动方向
		if (this.swipeDirection === 0) {
			console.log(Math.abs(moveY));
			//触发垂直操作
			if (Math.abs(moveY) > 4) {
				this.swipeDirection = 2;
        
				return true;
			}
			//触发水平操作
			if (Math.abs(moveX) > 4) {
				this.swipeDirection = 1;
				this.setData({ scrollY: false });
			}
			else {
				return;
			}

		}
		//禁用垂直滚动
		// if (this.data.scrollY) {
		//   this.setData({scrollY:false});
		// }

		this.lastMoveTime = e.timeStamp;
		//处理边界情况
		if (moveX > 0) {
			moveX = 0;
		}
		//检测最大左滑距离
		if (moveX < -this.maxMoveLeft) {
			moveX = -this.maxMoveLeft;
		}
		this.moveX = moveX;
		this.translateXMsgItem(e.currentTarget.id, moveX, 0);
	},
	ontouchend: function (e) {
		this.swipeCheckState = 0;
		var swipeDirection = this.swipeDirection;
		this.swipeDirection = 0;
		if (this.touchStartState === 1) {
			this.touchStartState = 0;
			this.setData({ scrollY: true });
			return;
		}
		//垂直滚动，忽略
		if (swipeDirection !== 1) {
			return;
		}
		if (this.moveX === 0) {
			this.showState = 0;
			//不显示菜单状态下,激活垂直滚动
			this.setData({ scrollY: true });
			return;
		}
		if (this.moveX === this.correctMoveLeft) {
			this.showState = 1;
			this.lastShowMsgId = e.currentTarget.id;
			return;
		}
		if (this.moveX < -this.thresholdMoveLeft) {
			this.moveX = -this.correctMoveLeft;
			this.showState = 1;
			this.lastShowMsgId = e.currentTarget.id;
		}
		else {
			this.moveX = 0;
			this.showState = 0;
			//不显示菜单,激活垂直滚动
			this.setData({ scrollY: true });
		}
		this.translateXMsgItem(e.currentTarget.id, this.moveX, 500);
		//this.translateXMsgItem(e.currentTarget.id, 0, 0);
	},

	getItemIndex: function (id) {
		var positions = this.data.positions;
		for (var i = 0; i < positions.length; i++) {
			if (positions[i].id == id) {
				return i;
			}
		}
		return -1;
	},
	deleteMsgItem: function (e) {
		var animation = wx.createAnimation({ duration: 200 });
		animation.height(0).opacity(0).step();
		this.animationMsgWrapItem(e.currentTarget.id, animation);
		var s = this;
		app.apiPost(app.apiList.delMyJob, { id: e.currentTarget.id},function(res){
			if(res.code == 200){
				wx.showToast({
					title: '删除成功！',
					icon: 'success',
					duration: 1000,
					mask: true,
					success: function () {
						var index = s.getItemIndex(e.currentTarget.id);
						s.data.positions.splice(index, 1);
						s.setData({ positions: s.data.positions });
					}
				})
				
			}
		})	
		// setTimeout(function () {
		// 	var index = s.getItemIndex(e.currentTarget.id);
		// 	s.data.positions.splice(index, 1);
		// 	s.setData({ positions: s.data.positions });
		// }, 200);
		this.showState = 0;
		this.setData({ scrollY: true });
	},
	translateXMsgItem: function (id, x, duration) {
		var animation = wx.createAnimation({ duration: duration });
		animation.translateX(x).step();
		this.animationMsgItem(id, animation);
	},
	animationMsgItem: function (id, animation) {
		var index = this.getItemIndex(id);
		var param = {};
		var indexString = 'positions[' + index + '].animation';
		param[indexString] = animation.export();
		this.setData(param);
	},
	animationMsgWrapItem: function (id, animation) {
		var index = this.getItemIndex(id);
		var param = {};
		var indexString = 'positions[' + index + '].wrapAnimation';
		param[indexString] = animation.export();
		this.setData(param);
	},

	getMyJobs: function(page){
		var that = this;
		app.apiGet(app.apiList.getMyJobs,{page:page},function(res){
			if (res.code == 200){
				let newpositions = that.data.positions.concat(res.data.positions);
				let newpageNum = ++that.data.pageNum;
				that.setData({
					positions: newpositions,
					nextPageUrl: res.data.next_page_url,
					pageNum: newpageNum
				})
			}
		})
	},



	//删除 or 下架
	onDeletePosTap: function (e) {
    var id = e.currentTarget.id;
    if (this.data.positions[this.getItemIndex(id)].issue == 2) {
      this.offMyJobFun(id);
    } else {
      this.deleteMsgItem(e);
    }
	},
	//长按删除 or 下架
	onDeletePosLongtap: function (e) {
    var id = e.currentTarget.id;
    if (this.data.positions[this.getItemIndex(id)].issue == 2) {
      this.offMyJobFun(id);
    } else {
      this.deleteMsgItem(e);
    }
	},
  offMyJobFun: function(id){
    var that = this;
    app.apiPost(app.apiList.offMyJob, { id: id }, function (res) {
      if (res.code == 200) {
        wx.showToast({
          title: '下架成功！',
          icon: 'success',
          duration: 1000,
          mask: true,
          success: function () {
            that.data.positions[that.getItemIndex(id)].issue = 1;
            that.setData({
              positions: that.data.positions
            })
           }
        })
      }
    })
  },

	//发布职位 or 刷新职位
	onReleasePosTap: function (e) {
		var id = e.currentTarget.id;
		if (this.data.positions[this.getItemIndex(id)].issue == 1){
			this.pushMyJobFun(id);
		}else{
			this.refreshMyJobFun(id);
		}
	},
	//长按发布职位 or 刷新职位
	onReleasePosLongTap: function (e) {
    var id = e.currentTarget.id;
    if (this.data.positions[this.getItemIndex(id)].issue == 1) {
      this.pushMyJobFun(id);
    } else {
      this.refreshMyJobFun(id);
    }
	},
	//发布职位
	pushMyJobFun: function(id){
		var that = this;
		app.apiPost(app.apiList.pushMyJob,{id:id},function(res){
			if(res.code == 200){
				wx.showToast({
					title: '发布成功！',
					icon: 'success',
					duration: 1000,
					mask: true,
					success: function () {
						that.data.positions[that.getItemIndex(id)].issue = 2;
						that.setData({
							positions: that.data.positions
						})
						
					}
				})
			}
		})
	},
	//刷新职位
	refreshMyJobFun: function(id){
		var that = this;
		app.apiPost(app.apiList.refreshMyJob, { id: id }, function (res) {
			if (res.code == 200) {
				wx.showToast({
					title: '刷新成功！',
					icon: 'success',
					duration: 1000,
					mask: true,
					success: function () {}
				})
			}
		})
	},
	//修改
	onUpdatePosTap: function(e){
		this.editMyJobFun(e.currentTarget.id)
	},
	onUpdatePosLongTap: function (e) {
		this.editMyJobFun(e.currentTarget.id)
	},
	//修改
	editMyJobFun: function(id){
		var that = this;
		app.apiGet(app.apiList.positionDetail, { id: id }, function (res) {
			if (res.code == 200) {
				var workYearsIndex, eduIndex;
				for (var i = 0; i < that.data.workYearsArray.length; i++) {
					if (res.data.workYears == that.data.workYearsArray[i].value) {
						workYearsIndex = i
						break;
					}
				}
				for (var j = 0; i < that.data.eduArray.length; j++) {
					if (res.data.education == that.data.eduArray[j].value) {
						eduIndex = j
						break;
					}
				}
				let dataJson = {
					name: res.data.positionName,
					salary: res.data.salary,
					workYearsIndex: workYearsIndex,
					eduIndex: eduIndex,
					positionFlag: res.data.flag,
					company_name: res.data.company,
					industry: res.data.industry,
					companyTag: res.data.tag,
					address: res.data.workAddress,
					email: res.data.contact,
					province: res.data.province,
					city: res.data.city
				}
				that.setData({
					positionObj: dataJson,
					'contentObj.content': res.data.content,
					currentTab: 0,
					isEdit: true,
					idEdit: res.data.id
				})
			}
		})
	},

	//点击tab切换
	swichNav: function (e) {
		var that = this;
		if (this.data.currentTab === e.target.dataset.current) {
			return false;
		} else {
			this.setData({
				currentTab: e.target.dataset.current
			})
			if (e.target.dataset.current == 0){
				this.setData({
					positionObj: {},//初始化职位信息
					contentObj: {},//初始化模版信息
					agreement: false,// 协议
					isEdit: false,//是否编辑
					idEdit:''//编辑职位id
				})
			}
		}
		

	},
	//去协议页
	toAgreement: function(){
		wx.navigateTo({
			url: '/pages/agreement/agreement',
		})
	},
	//share 统一分享
	onShareAppMessage: function (res) {
		if (res.from === 'button') {
			// 来自页面内转发按钮
			console.log(res.target)
		}
		return {
			title: '财咖｜会计招聘找工作',
			path: '/pages/index/index',
			imageUrl: '/images/share.jpg',
			success: function (res) {
				// 转发成功
			},
			fail: function (res) {
				// 转发失败
			}
		}
	},
	//进入详情页面
	positionDetailTap: function (e) {
		var id = e.currentTarget.dataset.positionId;
		wx.navigateTo({
			url: '/pages/detail/detail?id=' + id,
		})
	}
})